/**
 * Copyright (c) 2010 Abadi Kurniawan, Brian Dukes
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package hackathon.android.mymessageinbox;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.TextView;

/**
 * @author Abadi Kurniawan, Brian Dukes
 *
 */
public class MyAdapter extends BroadcastReceiver implements ListAdapter {
	LinkedList<Message> messages;
	private LayoutInflater mInflater;
	private DataSetObserver observer;
	private MyDatabase dbHelper;
	private String userName;
	
	public MyAdapter(Context context, String userName)
	{
        mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        messages = new LinkedList<Message>();
        dbHelper = new MyDatabase(context);
        this.userName = userName;
        List<Message> oldMessage = dbHelper.selectAll(userName);
        
        for (Message message : oldMessage) {
			messages.add(message);
		}
	}
	
	public void close()
	{
		dbHelper.close();
	}

	@Override
	public boolean areAllItemsEnabled() {
		return true;
	}

	@Override
	public boolean isEnabled(int position) {
		return true;
	}

	@Override
	public int getCount() {
		return messages.size();
	}

	@Override
	public Object getItem(int position) {
		return messages.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public int getItemViewType(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.list_item, parent, false);
			holder = new ViewHolder();
			holder.subject = (TextView)convertView.findViewById(R.id.item_subject_text);
			holder.from = (TextView)convertView.findViewById(R.id.item_from_text);
			holder.date = (TextView)convertView.findViewById(R.id.item_date_text);
			convertView.setTag(holder);
		}else {
			holder = (ViewHolder)convertView.getTag();
		}
		
		Message msg = messages.get(position);
		holder.subject.setText(msg.getSubject());
		holder.from.setText(msg.getSender());
		holder.date.setText(DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(msg.getDate()));
		
		return convertView;
	}

	@Override
	public int getViewTypeCount() {
		return 1;
	}

	@Override
	public boolean hasStableIds() {
		return true;
	}

	@Override
	public boolean isEmpty() {
		return false;
	}

	@Override
	public void registerDataSetObserver(DataSetObserver observer) {
		this.observer = observer;
	}

	@Override
	public void unregisterDataSetObserver(DataSetObserver observer) {
		this.observer = null;
	}
	
	public void notifyDataSetChange()
	{
		if (this.observer != null) {
			this.observer.onChanged();
		}
	}

	static class ViewHolder
	{
		TextView subject;
		TextView from;
		TextView date;
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		if(bundle != null)
		{
			String result = bundle.getString(MessageService.EXTRA_MESSAGES);
			JSONArray jsonArray;
			try {
				jsonArray = new JSONArray(result);
				if (jsonArray.length() > 0)
				{
					for(int i = jsonArray.length() - 1; i >= 0; i--)
					{
						JSONObject json = jsonArray.getJSONObject(i);
						Message msg = new Message();
						msg.setSubject(json.getString("Subject"));
						msg.setSender(json.getString("FromUserName"));
						msg.setToUserName(json.getString("ToUserName"));
						msg.setMessageId(json.getInt("MessageID"));
						msg.setConversation(json.getString("Conversation"));
						msg.setToRole(json.getString("ToRoleName"));
						SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						msg.setDate(df.parse(json.getString("MessageDate")));
//						msg.setDate(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).parse(json.getString("MessageDate")));
						msg.setStatus(json.getString("Status"));
						msg.setAllowReply(json.getBoolean("AllowReply"));
						msg.setBody(json.getString("Body"));
						msg.setOwner(userName);
						
						if (!checkIfMessageAlreadyExists(msg))
						{
							dbHelper.insert(msg);
							this.messages.addFirst(msg);
						}
					}
					notifyDataSetChange();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
	}
	
	private boolean checkIfMessageAlreadyExists(Message msg) {
		for (Message oldMessage : this.messages) {
			if (oldMessage.getMessageId() == msg.getMessageId())
			{
				return true;
			}
		}
		
		return false;
	}
}
